const { NAME_OR_PASSWORD_IS_REQUIRED, USER_IS_EXIST, SERVER_ERR } = require("../config/error");
const userService = require("../service/user.service");

const verifyUser = async (ctx, next) => {
  try {
    const { name, password } = ctx.request.body;
    if (!name || !password) {
      ctx.app.emit("error", NAME_OR_PASSWORD_IS_REQUIRED, ctx);
      return;
    }
    const users = await userService.findName(name);
    if (users.length) {
      ctx.app.emit("error", USER_IS_EXIST, ctx);
      return;
    }
    await next();
  } catch (error) {
    ctx.error = error;
    ctx.app.emit("error", SERVER_ERR, ctx);
  }
};
module.exports = verifyUser;
